package org.aceor.mddal.common.sqlparser.result.object;

import com.alibaba.druid.sql.ast.SQLOrderingSpecification;
import com.google.common.base.Objects;

/**
 * Created by lxue on 16/3/21.
 */
public class OrderByColumn {
    /**
     * 这里只存储name属性,不需要存储table(即owner)属性
     * 而table属性会在AbstractMysqlVisitor中均做处理
     */
    private String name;

    private OrderByType orderByType;

    /**
     * order by的列存在三种情况:
     * 1. select列中不存在.select id from table_a order by age
     * 2. select列中存在,且有别名.select id, age AS stuAge from table_a order by age
     * 3. select列中存在,且没有别名.select id, age from table_a order by age
     * 情况1,后期会被添加新列age(和情况3一样的语句)
     * 情况2,由于在分库分表下返回的多个ResultSet中的列名是别名,
     * 因此无法通过OrderByColumnName来做排序,所以这个时候需要存储"stuAge"到alias字段中
     */
    private String alias;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public OrderByType getOrderByType() {
        return orderByType;
    }

    public void setOrderByType(OrderByType orderByType) {
        this.orderByType = orderByType;
    }

    public String getAlias() {
        return alias;
    }

    public void setAlias(String alias) {
        this.alias = alias;
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("name", name)
                .add("alias", alias)
                .add("type", orderByType)
                .toString();
    }

    public boolean isAsc() {
        if (null == orderByType) {
            return true;
        } else {
            return OrderByType.ASC == orderByType;
        }
    }

    public enum OrderByType {
        ASC,DESC
        ;

        public static OrderByType valueof(SQLOrderingSpecification orderingSpecification) {
            if (null == orderingSpecification) {
                return ASC;
            } else {
                return valueOf(orderingSpecification.toString());
            }
        }
    }
}
